package com.liu.algorithm01;

public class BinarySearch03 {
    /*
        给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。
        如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
        请必须使用时间复杂度为 0(1ogn)的算法。
    */
    public static void main(String[] args) {
        int[] arr = {1, 3, 3, 3, 5, 6};
        int i1 = searchInsert01(arr, 3);
        System.out.println(i1);
        System.out.println("-------------------------------------------");
        int i2 = searchInsert02(arr, 3);
        System.out.println(i2);
    }

    // 方法1
    private static int searchInsert01(int[] a, int target) {
        int low = 0;
        int high = a.length - 1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];
            if (target <= midVal) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }

    // 方法2
    private static int searchInsert02(int[] a, int target) {
        int low = 0;
        int high = a.length - 1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            long midVal = a[mid];
            if (target < midVal) {
                high = mid - 1;
            } else if (target > midVal) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
        return low;
    }
}
